package com.za.upgradeshield;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ShieldInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShieldInterceptor.class);

    private final ShieldProperties properties;
    private final ShieldResponseBuilder responseBuilder;

    public ShieldInterceptor(ShieldProperties properties, ShieldResponseBuilder builder) {
        this.properties = properties;
        this.responseBuilder = builder;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.debug("enter shield interceptor ... ");
        if (!properties.isEnabled()) return true;

        String uri = request.getRequestURI();
        List<String> paths = properties.getPaths();
        if (paths != null && paths.size()>0) {
            for (String path : paths) {
                if (path.equals(uri)) {
                    LOGGER.info("shield request:{} ", uri);
                    ResultUtil.responseJson(response, responseBuilder.build(request, uri));
                    return false;
                }
            }
        }

        return true;
    }
}
